package com.clock.service.impl;

import com.clock.common.domain.R;
import com.clock.common.utils.LocalDateTimeUtil;
import com.clock.domain.entity.DailyRecord;
import com.clock.domain.entity.User;
import com.clock.domain.vo.StudyAnalysisVo;
import com.clock.mapper.DailyRecordMapper;
import com.clock.mapper.TagMapper;
import com.clock.service.ContentUserLikeService;
import com.clock.service.SignInService;
import com.clock.service.StudyAnalysisService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class StudyAnalysisServiceImpl implements StudyAnalysisService {
/*
    分析 需要的东西 ，当月签到总次数 ， 打败了 多少多少人 ；
                   当月总学习时长
                   根据点赞 标签 找到 用户最感兴趣的 三个话题
                   分析写作行为
                   行为记录 ~~~~ 没法做
                   每天 学习 时间曲线
                   按每天来看的话 学习密度
                   总结
*/

    @Resource
    SignInService signInService; // 签到

    @Resource
    ContentUserLikeService contentUserLikeService; // 点赞

    @Resource
    TagMapper tagMapper; //获取啥啥标签

    @Resource
    DailyRecordMapper dailyRecordMapper;

    @Override
    public StudyAnalysisVo getStudyAnalysis(User user) {
        StudyAnalysisVo studyAnalysisVo = new StudyAnalysisVo();
        studyAnalysisVo.setUserId(user.getUserId());
        if(user.getUserName()!=null){
            studyAnalysisVo.setUserName(user.getUserName());
        }
        //先判断签到天数够不够
        R signCount = signInService.getSignCount(studyAnalysisVo.getUserId());
        Long data = (Long)signCount.getData();
        if(data<7 || data==null){
            return studyAnalysisVo;
        }
        studyAnalysisVo.setSignAmount(data);
        //获得当月总学习时长
        studyAnalysisVo = getStudyTime(studyAnalysisVo);
        //最爱点赞的模块
        studyAnalysisVo = getLikeByTag(studyAnalysisVo);
        //写的哪个方面的帖子比较多
        studyAnalysisVo = getLikeByPost(studyAnalysisVo);
        //学习曲线
        List<DailyRecord> dailyRecords = dailyRecordMapper.queryRecordsByOneMouth(user.getUserId());
        studyAnalysisVo = getStudyTimeToOneDay(studyAnalysisVo,dailyRecords);
        //学习密度分析   （星期几学习时间较多  ，  哪个时间段学习最多）
        studyAnalysisVo = getStudyTimeInWhichTimeAndDay(studyAnalysisVo,dailyRecords);
        //总结
        studyAnalysisVo = getStudySummary(studyAnalysisVo);

        return studyAnalysisVo;
    }

    @Override
    public String[] getUserInfTag(User user) {
        String[] tags = new String[2];
        StudyAnalysisVo studyAnalysisVo = new StudyAnalysisVo();
        studyAnalysisVo.setUserId(user.getUserId());
        studyAnalysisVo = getLikeByTag(studyAnalysisVo);
        studyAnalysisVo = getLikeByPost(studyAnalysisVo);
        tags[0] = studyAnalysisVo.getLikePostTag();
        tags[1] = studyAnalysisVo.getIsLikeTag();
        return tags;
    }

    //获得当月总的签到天数
    private StudyAnalysisVo getSignCount(StudyAnalysisVo studyAnalysis){
        R signCount = signInService.getSignCount(studyAnalysis.getUserId());
        Long data = (Long)signCount.getData();
        if(data==null){
            return studyAnalysis;
        }
        studyAnalysis.setSignAmount(data);
        return studyAnalysis;
    }

    //获得当月总学习时长
    private StudyAnalysisVo getStudyTime(StudyAnalysisVo studyAnalysis){
        Long queryAllByStudyTimeOneMouth = dailyRecordMapper.queryAllByStudyTimeOneMouth(studyAnalysis.getUserId());
        if(queryAllByStudyTimeOneMouth==null){
            return studyAnalysis;
        }
        studyAnalysis.setStudyAllTime(queryAllByStudyTimeOneMouth);
        return studyAnalysis;
    }

    //最爱点赞的模块
    private StudyAnalysisVo getLikeByTag(StudyAnalysisVo studyAnalysis){
        //获得当月点赞的帖子
        String bestLikeTag = contentUserLikeService.queryUserBestLikeTag(studyAnalysis.getUserId());
        if(!bestLikeTag.equals("")){
            studyAnalysis.setIsLikeTag(bestLikeTag);
        }
        return studyAnalysis;
    }

    //写的哪个方面的帖子比较多
    private StudyAnalysisVo getLikeByPost(StudyAnalysisVo studyAnalysis){
        String queryOneTagNameByPostLike = tagMapper.queryOneTagNameByPostLike(studyAnalysis.getUserId());
        if(queryOneTagNameByPostLike==null){
            return studyAnalysis;
        }
        studyAnalysis.setLikePostTag(queryOneTagNameByPostLike);
        return studyAnalysis;
    }

    //学习曲线
    private StudyAnalysisVo getStudyTimeToOneDay(StudyAnalysisVo studyAnalysis,List<DailyRecord> dailyRecords){
        //天数
        int daysOfMonth = LocalDateTimeUtil.getDaysOfMonth(new Date());
        Integer day[] = new Integer[daysOfMonth];
        for(int i = 0 ; i < daysOfMonth ; i++){
            day[i] = i+1;
        }
        studyAnalysis.setDay(day);

        if(dailyRecords.isEmpty()){
            String studyContent[] = new String[daysOfMonth];
            Long studyTime[] = new Long[daysOfMonth];
            studyAnalysis.setStudyContent(studyContent);
            studyAnalysis.setStudyTime(studyTime);
            return studyAnalysis;
        }

        String studyContent[] = new String[daysOfMonth];
        Long studyTime[] = new Long[daysOfMonth];

        for (DailyRecord dailyRecord : dailyRecords) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dailyRecord.getCreateTime());
            int i = calendar.get(Calendar.DAY_OF_MONTH);
            //对应学习内容
            if(studyContent[i-1]!=null){
                studyContent[i-1] += dailyRecord.getStudyContent()+"  ";
            }else{
                studyContent[i-1] = dailyRecord.getStudyContent()+"  ";
            }
            //对应学习时间
            if(studyTime[i-1]!=null){
                studyTime[i-1] += dailyRecord.getStudyTime();
            }else{
                studyTime[i-1] = dailyRecord.getStudyTime();
            }
        }

        for(int i = 0 ; i < daysOfMonth ; i++){
            if(studyTime[i]==null){
                studyTime[i]= 0l;
            }
        }

        studyAnalysis.setStudyContent(studyContent);
        studyAnalysis.setStudyTime(studyTime);

        return studyAnalysis;
    }

    //学习密度分析   （星期几学习时间较多  ，  哪个时间段学习最多）
    private StudyAnalysisVo getStudyTimeInWhichTimeAndDay(StudyAnalysisVo studyAnalysis,List<DailyRecord> dailyRecords){
        //星期几学习时间较多
        String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,1);
        int dayOfMouthOneWeek = calendar.get(Calendar.DAY_OF_WEEK)-1;

        Long[] studyTime = studyAnalysis.getStudyTime();
        
        Long maxTimeDay[] = new Long[7];
        Long maxTime = 0L;
        int maxIndex = 0;
        for (int i = 0; i < studyTime.length; i++) {
            int index = (i+dayOfMouthOneWeek)%7;
            if(maxTimeDay[index]!=null&&studyTime[i]!=null){
                maxTimeDay[index] += studyTime[i];
            }else{
                maxTimeDay[index] = studyTime[i];
            }
            if(maxTimeDay[index]!=null && maxTime<maxTimeDay[index]){
                maxTime = maxTimeDay[index];
                maxIndex = index;
            }
        }

        studyAnalysis.setMaxDay(weeks[maxIndex]);
        studyAnalysis.setMaxDayStudyTime(maxTime);
        
        //哪个时间段学习最多
        int studyTimeSlot[] = new int[24];
        int maxTimeSlot = 0;
        for (DailyRecord dailyRecord : dailyRecords) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(dailyRecord.getCreateTime());
            int i = calendar1.get(Calendar.HOUR_OF_DAY);
            studyTimeSlot[i]++;
            maxTimeSlot = Math.max(maxTimeSlot,studyTimeSlot[i]);
        }

        int maxSlot = 0;
        for(int i = 0 ; i < 24 ; i++){
            if (maxTimeSlot == studyTimeSlot[i]){
                maxSlot = i;
            }
        }

        studyAnalysis.setMaxTimeSlot(maxSlot+"点~"+(maxSlot+1)+"点");

        //最爱的学习内容分析
        String[] studyContent = studyAnalysis.getStudyContent();
        if(studyContent!=null){
            HashMap<String,Integer> hashMap = new HashMap<>();

            for (String s : studyContent) {
                if(s!=null){
                    if(hashMap.containsKey(s)){
                        hashMap.put(s,hashMap.get(s)+1);
                    }else{
                        hashMap.put(s,1);
                    }
                }
            }

            Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
            int maxStudy = 0;
            String maxStudyContent = new String();
            for (Map.Entry<String, Integer> entry : entries) {
                if(entry.getValue() > maxStudy){
                    maxStudy = entry.getValue();
                    maxStudyContent = entry.getKey();
                }
            }
            studyAnalysis.setBestLikeStudyContent(maxStudyContent);
        }

        return studyAnalysis;
    }

    //分析总结
    private StudyAnalysisVo getStudySummary(StudyAnalysisVo studyAnalysis){
        StringBuilder summary = new StringBuilder("非常开心您已经坚持了"
                +studyAnalysis.getSignAmount()+"天的学习;\n");

        if(studyAnalysis.getBestLikeStudyContent()!=null&&
                (studyAnalysis.getBestLikeStudyContent().equals(studyAnalysis.getIsLikeTag())
                || studyAnalysis.getBestLikeStudyContent().equals(studyAnalysis.getLikePostTag()))){
            summary.append("看来您真的很喜欢"+studyAnalysis.getBestLikeStudyContent()+"这个方面的内容呢,继续加油吧;\n");
        }

        String maxTimeSlot = studyAnalysis.getMaxTimeSlot();
        if(maxTimeSlot!=null){
            String[] split = maxTimeSlot.split("点");
            int intValue = Integer.valueOf(split[0]).intValue();
            summary.append("您喜欢从"+intValue+"点开始学习。");
            if(intValue>=0&&intValue<=5){
                intValue = 0;
            }
            if(intValue>=6 && intValue<= 10){
                intValue = 6;
            }
            if(intValue>=11 && intValue<= 13){
                intValue = 11;
            }
            if(intValue>=14 && intValue<= 18){
                intValue = 14;
            }
            if(intValue>=19 && intValue<= 24){
                intValue = 19;
            }

            switch (intValue){
                case 0 : summary.append("凌晨要注意休息,不要被卷王蒙蔽了双眼;\n");break;
                case 6 : summary.append("美好的早晨需要从一杯热牛奶开始;\n");break;
                case 11 : summary.append("不管您是不是南方人,中午都要保证充足的睡眠时间;\n");break;
                case 14 : summary.append("下午不会打小盹,正是最好的学习时间;\n");break;
                case 19 : summary.append("晚上要浅浅卷一下，不要卷太晚哦;\n");break;
                default: break;
            }
        }

        String maxDay = studyAnalysis.getMaxDay();
        if(maxDay !=null){
            summary.append("您最喜欢在"+maxDay+"学习。");
            String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
            for (int i = 0; i < weeks.length; i++) {
                if(maxDay.equals(weeks[i])){
                    if(i>0&&i<6){
                        summary.append("不是周末还卷,您才是合格的卷王;\n");
                    }else{
                        summary.append("周末开始卷，这叫小小卷;\n");
                    }
                    break;
                }
            }
            studyAnalysis.setSummary(summary.toString());
        }

        return studyAnalysis;
    }


}
